package com.zb.config.inteceptor;

import cn.dev33.satoken.router.SaRouter;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zb.entity.AccounLoginInfo;
import com.zb.redis.RedisLoginTokenUtil;
import com.zb.utils.IgnorePathUtil;
import com.zb.utils.RequestUtil;
import com.zb.utils.TokenUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * pc 端拦截器
 * @Author WEN
 * @Date 2023/7/28 0028
 **/
@Configuration
public class SysPCInteceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!RequestUtil.isPc()) {
            return true;
        }
        if (SaRouter.match(IgnorePathUtil.ignorePath()).isHit) {
            return true;
        }
        String accessToken = TokenUtil.getToken(request);
        if (StringUtils.isBlank(accessToken) || !RedisLoginTokenUtil.hasByAccessToken(accessToken)) {
            throw new LoginException("登录已过期，请重新登录！");
        }

        if (SaRouter.match(IgnorePathUtil.loginAuthoriIgnorePath()).isHit) {
            return true;
        }

        AccounLoginInfo logintInfo = RedisLoginTokenUtil.getAccountLoginInfoByAccessToken(accessToken);
        if (null == logintInfo.getCustAccId()) {
            throw new LoginException("登录认证企业失败，请登录后选择企业！");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
